//
//  MSAFNManage.swift
//  SwiftWeibo
//
//  Created by 牟松 on 16/8/9.
//  Copyright © 2016年 DoNews. All rights reserved.
//

import UIKit
import AFNetworking

enum requestMethod {
    case GET
    case POST
}

class MSAFNManage: AFHTTPSessionManager {
    
    
    static let shared: MSAFNManage = {
        // 实例化对象
        let instance = MSAFNManage()
        
        // 设置响应反序列化支持的数据类型
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        // 返回对象
        return instance
    }()// 单利
    
    lazy var userAccount = MSUserAccountInfoModel()
    
    var userLogin: Bool {
        return userAccount.access_token != nil
    }
    
    
    func accresstokenRequest(method: requestMethod = .GET, urlString: String, params: [String: AnyObject]?, completion: (json: AnyObject?, isSuccess: Bool)->()) {
        
        var params = params
        
        if params == nil {
            params = [String: AnyObject]()
        }
        
        params?["access_token"] = userAccount.access_token
        
        request(method: method, urlString: urlString, params: params, completion: completion)
    }
    
    // MARL: - 集成get和post方法
    func request(method: requestMethod = .GET, urlString: String, params: [String: AnyObject]?, completion: (json: AnyObject?, isSuccess: Bool)->()) {
        
        let success = { (task: URLSessionDataTask, json: AnyObject?)->() in
            completion(json: json, isSuccess: true)
        }
        
        let failed = { (task: URLSessionDataTask?, error: Error)->() in
            print("网络请求失败 error = \(error)")
            
            guard let task = task else {
                return
            }
            if (task.response as! HTTPURLResponse).statusCode == 403 {
                print("token不正确")
                
                // 发通知重新登录
                NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: WBUserShouldLoginNotification), object: "bad token")
            }
            
            completion(json: nil, isSuccess: false)
        }
        
        
        if method == .GET {
            get(urlString, parameters: params, progress: nil, success: success, failure: failed)
        } else {
            post(urlString, parameters: params, progress: nil, success: success, failure: failed)
        }
    }

}
